//
//  YWKeepWatchMissionManager.m
//  maintain
//
//  Created by Kyo on 16/2/20.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWKeepWatchMissionManager.h"
#import "YWDBTool.h"
#import "YWKeepWatchDBManager.h"
#import "YWCommonTool.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWResourceManager.h"
#import "WMHttpTool.h"
#import "YWPatrolPicture.h"
#import "YWBuildingManager.h"
#import "MJExtension.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "YWBuilding.h"
#import "NSDate+Additions.h"
#import "YWEquipmentManager.h"
#import "YWEquipment.h"
#import "YWCirculationManager.h"
#import "YWMissionManager.h"
#import "YWReportTroubleModel.h"
#import "YWKeepWatchMission.h"
#import "YWNotifyManager.h"
#import "YWScanEquipmentNotMatchVC.h"
#import "YWDoKeepWatchMissionTableViewController.h"
#import "YWReplyDBManager.h"
#import "YWReply.h"
#import "YWLogRecordTool.h"
#import "YWEwinManager.h"
#import <Bugly/Bugly.h>

static BOOL isUploading = NO;

@interface YWKeepWatchMissionManager ()
@property (nonatomic, strong) dispatch_group_t group;
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
//@property (nonatomic, strong) dispatch_semaphore_t signal;
@end
@implementation YWKeepWatchMissionManager
YWSingletonM(Manager)

- (dispatch_group_t)group{
    if (!_group) {
        _group = dispatch_group_create();
    }
    return _group;
}

//- (dispatch_queue_t)serialQueue{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadKeepWatchRecordserialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}
//
//- (dispatch_semaphore_t)signal{
//    if (!_signal) {
//        _signal = dispatch_semaphore_create(1);
//    }
//    return _signal;
//}

- (BOOL)updateKeepWatchMissionWithArray:(NSArray*)keepWatchMissions{
    return [[YWKeepWatchDBManager shareManager] updateKeepWatchMissionWithArray:keepWatchMissions];
}

- (BOOL)updateKeepWatchDeleteStatusWithMissionId:(NSInteger)keepWatchMissionId{
    return [[YWKeepWatchDBManager shareManager] updateKeepWatchDeleteStatusWithMissionId:keepWatchMissionId];
}

- (NSArray*)allKeepWatchMissions{
    return [[YWKeepWatchDBManager shareManager] allKeepWatchMissions];
}

- (NSArray *)keepWatchMissionsWithPage:(NSInteger)page{
    return [[YWKeepWatchDBManager shareManager] keepWatchMissionsWithPage:page];
}

- (NSString *)allKeepWatchMissionIds{
    return [[YWKeepWatchDBManager shareManager] allKeepWatchMissionIds];
}

- (YWKeepWatchMission*)keepWatchMissionWithMissionId:(NSInteger)keepWatchMissionId{
    return [[YWKeepWatchDBManager shareManager] keepWatchMissionWithMissionId:keepWatchMissionId];
}

-(NSArray *)keepWatchMissionWithLocationId:(NSInteger)locationId{
    return [[YWKeepWatchDBManager shareManager] keepWatchMissionWithLocationId:locationId];
}

- (BOOL)updatePatrollineRecordWithArray:(NSArray*)patrollineRecords{
    return  [[YWKeepWatchDBManager shareManager] updatePatrollineRecordWithArray:patrollineRecords];
}

- (BOOL)updatePatrollineRecordWithNewWorkData:(NSArray*)patrollineRecords{
    return [[YWKeepWatchDBManager shareManager] updatePatrollineRecordWithNewWorkData:patrollineRecords];
}

- (YWPatrollineRecord *)latestPatrollineRecordWithUniqueTag:(NSString *)uniqueTag{
    return  [[YWKeepWatchDBManager shareManager] latestPatrollineRecordWithUniqueTag:uniqueTag];
}

- (NSInteger)todayFinishCountWithPatrolLineId:(NSInteger)patrolLineId keepWatchMissionId:(NSInteger)keepWatchMissionId{
    return [[YWKeepWatchDBManager shareManager] todayFinishCountWithPatrolLineId:patrolLineId keepWatchMissionId:keepWatchMissionId];
}

- (NSArray*)patrollineRecordWithKeepWatchMission:(YWKeepWatchMission*)keepWatchMission page:(NSInteger)page{
    return [[YWKeepWatchDBManager shareManager] patrollineRecordWithKeepWatchMission:keepWatchMission page:page];
}
- (NSArray*)patrolLineRecordWithPage:(NSInteger)page{
    return [[YWKeepWatchDBManager shareManager] patrolLineRecordWithPage:page];
}

-(BOOL)updateReadStatusWithKeepWatchMissionId:(NSInteger)keepWatchMissionId{
    return [[YWKeepWatchDBManager shareManager] updateReadStatusWithKeepWatchMissionId:keepWatchMissionId];
}

- (BOOL)updatePatrolPointRecordWithArray:(NSArray*)patrolPointRecords{
    return [[YWKeepWatchDBManager shareManager] updatePatrolPointRecordWithArray:patrolPointRecords];
}

- (NSArray*)patrolPointRecordWithUniqueTag:(NSString*)uniqueTag{
    return [[YWKeepWatchDBManager shareManager] patrolPointRecordWithUniqueTag:uniqueTag];
}

- (NSInteger)countOfPatrolPointRecordWithUniqueTag:(NSString*)uniqueTag{
    return [[YWKeepWatchDBManager shareManager] countOfPatrolPointRecordWithUniqueTag:uniqueTag];
}

- (NSArray*)patrolPointRecordWithLocationId:(NSInteger)locationId{
    return [[YWKeepWatchDBManager shareManager] patrolPointRecordWithLocationId:locationId];
}

- (NSArray *)patrolPointRecordsWithUploadStatusFail{
    return [[YWKeepWatchDBManager shareManager] patrolPointRecordsWithUploadStatusFail];
}

- (NSArray *)uploadFailedPatrolPointRecords{
    return [[YWKeepWatchDBManager shareManager] uploadFailedPatrolPointRecords];
}

- (BOOL)updatePatrolPointRecordUploadStatus:(YWPatrolPointRecordUploadStatus)uploadStatus pointRecordId:(NSString*)recordId{
    return [[YWKeepWatchDBManager shareManager] updatePatrolPointRecordUploadStatus:uploadStatus pointRecordId:recordId];
}

- (BOOL)updatePatrolPictureWithArray:(NSArray*)patrolPictures{
    return [[YWDBTool shareDBTool] updatePatrolPictureWithArray:patrolPictures];
}

- (BOOL)updatePatrolPictureWithNewWorkData:(NSArray*)patrolPictures{
    return [[YWDBTool shareDBTool] updatePatrolPictureWithNewWorkData:patrolPictures];
}

- (NSArray*)recordPictureWithRecordId:(NSString*)recordId recordType:(YWPictureRecordType)recordType{
    return [[YWDBTool shareDBTool] recordPictureWithRecordId:recordId recordType:recordType];
}

- (NSArray*)allPatrolLocationWithPatrolLineId:(NSInteger)patrolLineId{
    return [[YWKeepWatchDBManager shareManager] allPatrolLocationWithPatrolLineId:patrolLineId];
}

- (BOOL)isExistLocationWithPatrolLineId:(NSInteger)patrolLineId{
    return [[YWKeepWatchDBManager shareManager] isExistLocationWithPatrolLineId:patrolLineId];
}

- (NSArray*)patrolLocationNoteWithLocationId:(NSInteger)locationId lineIds:(NSArray*)patrolLineIdArray{
    return [[YWKeepWatchDBManager shareManager] patrolLocationNoteWithLocationId:locationId lineIds:patrolLineIdArray];
}

- (YWPatrolLine *)patrolLineWithPatrolLineId:(NSInteger)patrolLineId{
    return [[YWKeepWatchDBManager shareManager] patrolLineWithPatrolLineId:patrolLineId];
}

- (NSArray *)needRequestPatrolLines{
    return [[YWKeepWatchDBManager shareManager] needRequestPatrolLines];
}

- (NSInteger)sortWithLocationId:(NSInteger)locationId patrolLineId:(NSInteger)patrolLineId{
    return [[YWKeepWatchDBManager shareManager] sortWithLocationId:locationId patrolLineId:patrolLineId];
}

- (NSArray*)patrolLineDataWithPatrolLine:(YWPatrolLine*)patrolLine{
    NSMutableArray *dataArray = [NSMutableArray array];
    NSArray *patrolLocations = [self allPatrolLocationWithPatrolLineId:patrolLine.patrolLineId];
    NSString *locationName = nil;
    for (YWPatrolLineLocationRel *patrolLocation in patrolLocations) {
        locationName = [[YWBuildingManager shareManager]areaLocationWithLocationId:patrolLocation.locationId];
        [dataArray addObject:@{YWMissionManagerDicStatusType:@(YWPatrolPointStatusTypeUnfinish),YWMissionManagerDicLocation:locationName}];
    }
    return dataArray;
}

- (NSArray*)timeLineViewDataWithKeepWatchMission:(YWKeepWatchMission*)keepWatchMission orPatrolLineRecord:(YWPatrollineRecord*)patrolLineRecord
{
    NSMutableArray *dataArray = [NSMutableArray array];
    YWPatrollineRecord *record = nil;
    if (patrolLineRecord) {
        record = patrolLineRecord;
    }else{
        NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:keepWatchMission];
        record = [self latestPatrollineRecordWithUniqueTag:uniqueTag];
    }
    NSInteger patrolLineId = patrolLineRecord ? patrolLineRecord.patrolLineId : keepWatchMission.patrolLine.patrolLineId;
    
    if (record) {
        NSArray *finishPointRecords = [self patrolPointRecordWithUniqueTag:record.uniqueTag];
        NSArray *patrolLocations = [self allPatrolLocationWithPatrolLineId:patrolLineId];
        __block NSString *timeStr = nil;
        __block NSString *locationName = nil;
        for (YWPatrolLineLocationRel *patrolLocation in patrolLocations) {
            BOOL isFinish = NO;
            if (finishPointRecords.count) {
                NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", patrolLocation.locationId];
                NSArray *array = [[finishPointRecords filteredArrayUsingPredicate:searchPredicate] mutableCopy];
                if (array.count>0) {
                    YWPatrolPointRecord *patrolPointRecord = array[0];
                    isFinish = YES;
                    timeStr = [YWCommonTool showTime:patrolPointRecord.patrolTime/1000 andFormatter:KTimeFormatShortTimeDate];
                    if (patrolPointRecord.executor.userName.length) {
                        timeStr = [NSString stringWithFormat:@"%@ %@",patrolPointRecord.executor.userName,timeStr];
                    }
                    locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:patrolLocation.locationId];
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setValue:@(patrolPointRecord.status == YWPatrolpointRecordStatusNormal ? YWPatrolPointStatusTypeFinishNormal:YWPatrolPointStatusTypeFinishTrouble) forKey:YWMissionManagerDicStatusType];
                    [dic setValue:locationName forKey:YWMissionManagerDicLocation];
                    [dic setValue:timeStr forKey:YWMissionManagerDicTime];
                    [dic setValue:patrolPointRecord forKey:YWMissionManagerDicRecordObj];
                    [dataArray addObject:dic];
                }
            }
            
            if (!isFinish) {
                NSString *locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:patrolLocation.locationId];
                NSString *timeStr = @"【未巡】";
                [dataArray addObject:@{YWMissionManagerDicStatusType:@(YWPatrolPointStatusTypeUnfinish),YWMissionManagerDicLocation:locationName,YWMissionManagerDicTime:timeStr}];
            }
        }
        return dataArray;
    }
    
    return [self allPonintUnfinishWithPatrolLineId:patrolLineId];
    
}

-(NSArray*)allPonintUnfinishWithPatrolLineId:(NSInteger)patrolLineId
{
    NSMutableArray *dataArray = [NSMutableArray array];
    NSArray *patrolLocations = [self allPatrolLocationWithPatrolLineId:patrolLineId];
    NSString *locationName = nil;
    for (YWPatrolLineLocationRel *patrolLocation in patrolLocations) {
        locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:patrolLocation.locationId];
        NSString *timeStr = @"【未巡】";
        [dataArray addObject:@{YWMissionManagerDicStatusType:@(YWPatrolPointStatusTypeUnfinish),YWMissionManagerDicLocation:locationName,YWMissionManagerDicTime:timeStr}];
    }
    return dataArray;
}

- (NSArray*)detailViewTimeLineDataWithPatrollineRecord:(YWPatrollineRecord *)patrollineRecord{
    NSMutableArray *dataArray = [NSMutableArray array];
    if (patrollineRecord) {
        NSArray *finishPointRecords = [self patrolPointRecordWithUniqueTag:patrollineRecord.uniqueTag];
        NSArray *patrolLocations = [self allPatrolLocationWithPatrolLineId:patrollineRecord.patrolLineId];
        if (patrolLocations.count==0 && finishPointRecords.count>0) {
            NSMutableArray *locationsArray = [NSMutableArray array];
            for (YWPatrolPointRecord* patrolPointRecord in finishPointRecords) {
                YWPatrolLineLocationRel *patrolLocation = [[YWPatrolLineLocationRel alloc]init];
                patrolLocation.locationId = patrolPointRecord.locationId;
                [locationsArray addObject:patrolLocation];
            }
            patrolLocations = [[NSArray alloc]initWithArray:locationsArray];
        }
        NSString *timeStr = nil;
        NSString *locationName = nil;
        for (YWPatrolLineLocationRel *patrolLocation in patrolLocations) {
            BOOL isFinish = NO;
            for (YWPatrolPointRecord* patrolPointRecord in finishPointRecords) {
                if(patrolPointRecord.locationId == patrolLocation.locationId){
                    isFinish = YES;
                    timeStr = [YWCommonTool showTime:patrolPointRecord.patrolTime/1000 andFormatter:KTimeFormatShortTimeDate];
                    if (patrolPointRecord.executor.userName.length) {
                        timeStr = [NSString stringWithFormat:@"%@ %@",patrolPointRecord.executor.userName,timeStr];
                    }
                    locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:patrolLocation.locationId];
                    [dataArray addObject:@{YWMissionManagerDicStatusType:@(patrolPointRecord.status == YWPatrolpointRecordStatusNormal ? YWPatrolPointStatusTypeFinishNormal:YWPatrolPointStatusTypeFinishTrouble),YWMissionManagerDicLocation:locationName,YWMissionManagerDicTime:timeStr,YWMissionManagerDicRecordObj:patrolPointRecord?:@""}];
                    break;
                }
            }
            if (!isFinish) {
                NSString *locationName = [[YWBuildingManager shareManager]areaLocationNobuildingWithId:patrolLocation.locationId];
                NSString *timeStr = @"【未巡】";
                [dataArray addObject:@{YWMissionManagerDicStatusType:@(YWPatrolPointStatusTypeUnfinish),YWMissionManagerDicLocation:locationName,YWMissionManagerDicTime:timeStr}];
            }
        }
        return dataArray;
    }
    return [self allPonintUnfinishWithPatrolLineId:patrollineRecord.patrolLineId];
}

- (void)uploadFailPatrolPointRecords{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![YWLoginTool isLogin]) {
            return;
        }
        if (isUploading == YES) {
            return;
        }
        isUploading = YES;
        
        NSArray* uploadFailPointRecords = [self patrolPointRecordsWithUploadStatusFail];
        __block NSMutableArray *allPictures = [NSMutableArray array];
        __block NSMutableArray *postTroublePictures = [NSMutableArray array];
        [uploadFailPointRecords enumerateObjectsUsingBlock:^(NSArray*  _Nonnull recordsArray, NSUInteger idx, BOOL * _Nonnull stop) {
            [recordsArray enumerateObjectsUsingBlock:^(YWPatrolPointRecord* _Nonnull pointRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                //图片
                NSArray* pictures = [self recordPictureWithRecordId:pointRecord.patrolpointRecordId recordType:YWPictureRecordTypePatrol];
                [allPictures addObjectsFromArray:pictures];
                //关联的报障
                pointRecord.posTroubleArray = [[YWMissionManager shareManager] postTroubleArrayWithDetailUniqueTag:pointRecord.detailUniqueTag];
                [pointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSArray *pictures = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
                    [postTroublePictures addObjectsFromArray:pictures];
                }];
            }];
            [self handleWithRecords:recordsArray pictures:allPictures postTroublePicture:postTroublePictures];
            
            if (idx == uploadFailPointRecords.count-1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPushBackgroundUploadRecordSuccessNotification object:nil];
                });
            }
        }];
        
        isUploading = NO;
    });
}

- (void)startUploadRecord:(YWPatrolPointRecord*)pointRecord pictures:(NSArray*)pictures{
    if (!pointRecord) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableArray *postTroublePicures = [NSMutableArray array];
        [pointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray *pictures = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
            [postTroublePicures addObjectsFromArray:pictures];
        }];
        [self handleWithRecords:pointRecord?@[pointRecord]:nil pictures:pictures postTroublePicture:postTroublePicures];
    });
}

- (void)handleWithRecords:(NSArray*)records pictures:(NSArray*)pictures postTroublePicture:(NSArray*)postTroublePicures{
    dispatch_group_enter(self.group);
    if (pictures.count>0 || postTroublePicures.count>0) {
        [self uploadPictures:pictures postTroublePicture:postTroublePicures complete:^(BOOL isError) {
            [self uploadCompleteHandleWithRecord:records error:isError];
        }];
    }else{
        [self uploadCompleteHandleWithRecord:records error:NO];
    }
    dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
}

- (void)uploadPictures:(NSArray*)recordPictures postTroublePicture:(NSArray*)postTroublePictures complete:(void (^)(BOOL isError))completeBlock{
    __block BOOL error = NO;
    [[YWResourceManager shareManager]
     uploadPatrolPictureToAliyunOSS:recordPictures
     complete:^(BOOL isError, NSArray* uploadPictures) {
         error = isError;
         if (!isError) {
             [self updatePatrolPictureWithArray:uploadPictures];
             [[YWResourceManager shareManager]
              uploadLocalPictureToAliyunOSS:postTroublePictures
              isAvatar:NO
              complete:^(BOOL isError, NSArray* uploadPictures) {
                  error = isError;
                  if (!isError) {
                      //报障的图片不在bloc里返回，因为如果有多个报障，图片数组不能和报障信息一一对应，会造成图片混乱
                      [[YWResourceManager shareManager] savePicturesToDBWithArray:uploadPictures];
                  }
                  if (completeBlock) {
                      completeBlock(error);
                  }
              }];
         }else{
             if (completeBlock) {
                 completeBlock(error);
             }
         }
     }];
}

- (void)uploadCompleteHandleWithRecord:(NSArray*)recordArray error:(BOOL)isError{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (!isError) {
            [self submitKeepWatchRecord:recordArray];
        }else{
            [recordArray enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull pointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                [self updatePatrolPointRecordUploadStatus:YWPatrolPointRecordUploadStatusUnFinished pointRecordId:pointRecord.patrolpointRecordId];
            }];
            dispatch_group_leave(self.group);
        }
    });
}

- (void)submitKeepWatchRecord:(NSArray*)pointRecordArray{
    NSDictionary *requestHead = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = requestHead;
    if (requestHead == nil) {dispatch_group_leave(self.group);return;}
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [pointRecordArray enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull pointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
        YWBuilding *building = [[YWBuildingManager shareManager] buildingWithLocationId:pointRecord.locationId];
        [params setValue:building.buildingId.length>0 ? building.buildingId:@"" forKey:[NSString stringWithFormat:@"records[%lu].buildingId", (unsigned long)idx]];
        [params setValue:@(pointRecord.patrolLineId) forKey:[NSString stringWithFormat:@"records[%lu].patrolLine.patrolLineId", (unsigned long)idx]];
        [params setValue:@(pointRecord.keepWatchMissionId) forKey:[NSString stringWithFormat:@"records[%lu].keepWatchMissionId", (unsigned long)idx]];
        [params setValue:@(pointRecord.locationId) forKey:[NSString stringWithFormat:@"records[%lu].location.locationId", (unsigned long)idx]];
        NSString *uniqueTag = pointRecord.uniqueTag.length>0 ? pointRecord.uniqueTag:@"";
        [params setValue:uniqueTag forKey:[NSString stringWithFormat:@"records[%lu].uniqueTag", (unsigned long)idx]];
        [params setValue:pointRecord.note?:@"" forKey:[NSString stringWithFormat:@"records[%lu].note", (unsigned long)idx]];
        [params setValue:@(pointRecord.status) forKey:[NSString stringWithFormat:@"records[%lu].resultCode", (unsigned long)idx]];
        [params setValue:pointRecord.detailUniqueTag?:[NSString stringWithFormat:@"%@_%ld",uniqueTag,(long)pointRecord.locationId] forKey:[NSString stringWithFormat:@"records[%lu].detailUniqueTag", (unsigned long)idx]];
        
        NSArray* recordPic = [self recordPictureWithRecordId:pointRecord.patrolpointRecordId recordType:YWPictureRecordTypePatrol];
        [recordPic enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull picture, NSUInteger index, BOOL* _Nonnull stop) {
            [params setValue:picture.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].url", (unsigned long)idx,(unsigned long)index]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].thumbnailUrl", (unsigned long)idx,(unsigned long)index]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].previewUrl", (unsigned long)idx,(unsigned long)index]];
        }];
        [pointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTroubleModel, NSUInteger troubleIdx, BOOL * _Nonnull stop) {
            //报障信息
            [params setValue:reportTroubleModel.uniqueTag?:@"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].uniqueTag",(unsigned long)idx,(unsigned long)troubleIdx]];
            YWEquipment* equipment = reportTroubleModel.equipment;
            if (equipment && equipment.equipmentTypeId > 0) {
                [params setValue:@(equipment.equipmentTypeId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].equipmentType.equipmentTypeId",(unsigned long)idx,(unsigned long)troubleIdx]];
                [params setValue:equipment.equipmentId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].equipment.equipmentId",(unsigned long)idx,(unsigned long)troubleIdx]];
                [params setValue:@(equipment.locationId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].location.locationId",(unsigned long)idx,(unsigned long)troubleIdx]];
            }else{
                NSInteger locationId = reportTroubleModel.location.locationId;
                if (locationId==0 && pointRecordArray.count>0) {
                    YWPatrolPointRecord *pointRecord = pointRecordArray[0];
                    locationId = pointRecord.locationId;
                }
                [params setValue:@(locationId) forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].location.locationId",(unsigned long)idx,(unsigned long)troubleIdx]];
            }
            
            [params setValue:reportTroubleModel.qrcodeId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].qrcodeId",(unsigned long)idx,(unsigned long)troubleIdx]];
            [params setValue:reportTroubleModel.note?:@"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].note",(unsigned long)idx,(unsigned long)troubleIdx]];
            YWBuilding* building = reportTroubleModel.building;
            
            if (building==nil && reportTroubleModel.equipment.equipmentId.length) {
                building = [[YWBuildingManager shareManager] buildingWithEquipmentId:reportTroubleModel.equipment.equipmentId];
            }
            if (building == nil && reportTroubleModel.location.locationId>0) {
                building = [[YWBuildingManager shareManager] buildingWithLocationId:reportTroubleModel.location.locationId];
            }
            [params setValue:building.buildingId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].building.buildingId",(unsigned long)idx,(unsigned long)troubleIdx]];
            NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTroubleModel.troubleId maintenanceType:reportTroubleModel.maintenanceTypeId];
            [troublePicureArray enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger picIdx, BOOL* _Nonnull stop) {
                [params setValue:picture.bigPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].url",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
                [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].thumbnailUrl",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
                [params setValue:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].troubles[%lu].pictures[%lu].previewUrl",(unsigned long)idx,(unsigned long)troubleIdx,(unsigned long)picIdx]];
            }];
        }];
        
        long long executeTime = [YWCommonTool numberWithTime:pointRecord.patrolTime];
        [params setValue:@(executeTime) forKey:[NSString stringWithFormat:@"records[%lu].clientExecuteTime", (unsigned long)idx]];
        long long nowTime = [YWCommonTool numberWithTime:[[NSDate date] timeIntervalSince1970]*1000];
        [params setValue:@(nowTime) forKey:[NSString stringWithFormat:@"records[%lu].clientCurrentTime", (unsigned long)idx]];
    }];
    NSString *url = [YWCommonTool getSubmitKeepWatchRecordUrl];
    YWLog(@"%@", params);
    //保存请求前的参数日志
    NSString *logTag = [YWCommonTool randStringId];
    NSMutableDictionary * logDic = [[YWLogRecordTool shareLogRecordManager] getLogDictionaryWithModule:@"巡更" interface:url params:params headers:requestHead tag:logTag];
    [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:logDic];
    
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [pointRecordArray enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull pointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                [self updatePatrolPointRecordUploadStatus:YWPatrolPointRecordUploadStatusFinished pointRecordId:pointRecord.patrolpointRecordId];
            }];
            
            NSArray* reportTroubleArray = [YWReportTroubleModel mj_objectArrayWithKeyValuesArray:json];
            if (reportTroubleArray.count) {
                [reportTroubleArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
                    //保存流转信息
                    [[YWCirculationManager shareManager] updateCirculationInfoWithArray:reportTrouble.circulationInfos];
                    //更新关联表的troubleId
                    [[YWMissionManager shareManager] updateRecordAndPostTroubleRelTableUniqueTag:reportTrouble.uniqueTag newTroubleId:reportTrouble.troubleId];
                    //修改本地的troubleId
                    [[YWMissionManager shareManager] updatePostTroubleId:reportTrouble uniqueTag:reportTrouble.uniqueTag];
                }];
            }
            //保存请求成功的参数日志
            NSMutableDictionary * successDic =
            [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:@"无" logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:successDic];
            dispatch_group_leave(self.group);
        });
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            //保存请求失败的参数日志
            NSString * result = [NSString stringWithFormat:@"%s,error:%@", __func__, error.localizedDescription];
            NSMutableDictionary * failedDic = [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:result logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:failedDic];
            //上传错误参数
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                NSString *statusCode = [NSString stringWithFormat:@"statusCode: %@",@(response.statusCode).stringValue];
                [Bugly reportException:[NSException exceptionWithName:@"巡更接口错误" reason:statusCode userInfo:params]];
            }
            
            [pointRecordArray enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull pointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                //更新上传状态
                [self updatePatrolPointRecordUploadStatus:YWPatrolPointRecordUploadStatusUnFinished pointRecordId:pointRecord.patrolpointRecordId];
            }];
            dispatch_group_leave(self.group);
        });
    }];
}

- (YWKeepWatchJudgeType)judgeTypeWithMission:(YWKeepWatchMission*)keepWatchMission{
    //任务状态
    YWKeepWatchJudgeType type = YWKeepWatchJudgeTypeMatch;
    if (keepWatchMission.status==-1) {
        //[YWCommonTool showTextHUDWithContent:@"任务已撤回"];
        return YWKeepWatchJudgeTypeMissionHasCancel;
    }
    //任务的巡更星期
    BOOL istotay = NO;
    for (YWPatrolLineWeekRel* weekRel in keepWatchMission.patrolLine.weekRels) {
        NSInteger weekDay = [NSDate date].weekday;
        //周日是1，周一是2，周六是7
        if (weekRel.week == weekDay - 1) {
            istotay = YES;
            break;
        }
    }
    if (!istotay) {
        //[YWCommonTool showTextHUDWithContent:@"今天不是巡更日"];
        return YWKeepWatchJudgeTypeNotWeekDay;
    }
    //间隔时间是0的数据错误问题
    if (keepWatchMission.patrolLine.intervalMinute<=0) {
        return YWKeepWatchJudgeTypeOutOfMissionTime;
    }
    //是否在工作时间内
    NSTimeInterval currentIntrval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDate *currentDate = [NSDate dateWithTimeIntervalSince1970:currentIntrval/1000];
    NSDate *missionStartDate = [NSDate dateWithTimeIntervalSince1970:keepWatchMission.startDate/1000];
    NSDate *missionEndDate = [NSDate dateWithTimeIntervalSince1970:keepWatchMission.endDate/1000];
    BOOL rightDate = (currentDate.year == missionStartDate.year && currentDate.month== missionStartDate.month && currentDate.day == missionStartDate.day) || (currentDate.year == missionEndDate.year && currentDate.month== missionEndDate.month && currentDate.day == missionEndDate.day);
    if (rightDate) {
        //是任务的日期
    }else{
        if (!(keepWatchMission.startDate<=currentIntrval && currentIntrval<=keepWatchMission.endDate)) {
            return YWKeepWatchJudgeTypeOutOfMissionTime;
        }
    }
    
    NSString *todayStr = [YWCommonTool showDate:[[NSDate date] timeIntervalSince1970]];
    NSString *startStr= [NSString stringWithFormat:@"%@ %@:00",todayStr,keepWatchMission.startTime];
    NSTimeInterval startInterval = [YWCommonTool timeIntervalWithDatestring:startStr dateFormatter:KTimeFormatFullDateAndTime] *1000;
    
    NSString *endStr= [NSString stringWithFormat:@"%@ %@:00",todayStr,keepWatchMission.endTime];
    NSTimeInterval endInterval = [YWCommonTool timeIntervalWithDatestring:endStr dateFormatter:KTimeFormatFullDateAndTime] *1000;
    
    if (startInterval > endInterval) {
        //隔夜
        NSString *todayZeroTime = [YWCommonTool showDate:currentIntrval/1000];
//        endStr= [NSString stringWithFormat:@"%@ %@:00",todayZeroTime,keepWatchMission.endTime];
//        endInterval = [YWCommonTool timeIntervalWithDatestring:endStr dateFormatter:KTimeFormatFullDateAndTime] *1000;
        
        todayZeroTime = [NSString stringWithFormat:@"%@ 00:00:00",todayZeroTime];
        NSTimeInterval todayZeroTimeInterVal = [YWCommonTool timeIntervalWithDatestring:todayZeroTime dateFormatter:KTimeFormatFullDateAndTime]*1000;
        
        NSString *tomorrowZeroTime = [YWCommonTool showDate:[[NSDate dateTomorrow]timeIntervalSince1970]];
        tomorrowZeroTime = [NSString stringWithFormat:@"%@ 00:00:00",tomorrowZeroTime];
        NSTimeInterval tomorrowZeroTimeInterVal = [YWCommonTool timeIntervalWithDatestring:tomorrowZeroTime dateFormatter:KTimeFormatFullDateAndTime]*1000;
        
        
        NSDate *missionStartDate = [NSDate dateWithTimeIntervalSince1970:keepWatchMission.startDate/1000];
        NSDate *missionEndDate = [NSDate dateWithTimeIntervalSince1970:keepWatchMission.endDate/1000];
        //判断今天是不是任务的开始日期
        if (missionStartDate.year == [NSDate date].year && missionStartDate.month == [NSDate date].month && missionStartDate.day == [NSDate date].day) {
            if ((currentIntrval >= startInterval && currentIntrval <=tomorrowZeroTimeInterVal)) {
                return type;
            }else{
                return YWKeepWatchJudgeTypeOutOfMissionTime;
            }
        }else if (missionEndDate.year == [NSDate date].year && missionEndDate.month == [NSDate date].month && missionEndDate.day == [NSDate date].day){
            //判断今天是不是任务的结束日期
            if (currentIntrval<=endInterval) {
                return type;
            }else{
                return YWKeepWatchJudgeTypeOutOfMissionTime;
            }
        }
        else{
            if ((currentIntrval >= startInterval && currentIntrval <=tomorrowZeroTimeInterVal) || (currentIntrval>= todayZeroTimeInterVal && currentIntrval<=endInterval)) {
                return type;
            }else{
                return YWKeepWatchJudgeTypeOutOfMissionTime;
            }
        }
    }else if ([keepWatchMission.startTime isEqualToString:@"00:00"] && [keepWatchMission.endTime isEqualToString:@"00:00"]){
        return type;
    }else{
        //同一天  //不在任务的执行时间内
        if (!(currentIntrval >= startInterval && currentIntrval <= endInterval)) {
            return YWKeepWatchJudgeTypeOutOfMissionTime;
        }
    }
    return type;
}
- (NSString*)typeNameWithJudgeType:(YWKeepWatchJudgeType)judgeType{
    NSString *typeName = nil;
    switch (judgeType) {
        case YWKeepWatchJudgeTypeMissionHasCancel:
            typeName = NSLocalizedString(@"missionHasCancel", nil);//@"任务已撤回";
            break;
        case YWKeepWatchJudgeTypeNotWeekDay:
            typeName = NSLocalizedString(@"todayIsNotKeepWatchDay", nil);//@"今天不是巡更日";
            break;
        case YWKeepWatchJudgeTypeOutOfMissionTime:
            typeName = NSLocalizedString(@"currentTimeIsNotKeepWatchTime", nil);//@"不在每日巡更时间段内";
            break;
            
        default:
            break;
    }
    return typeName;
}
- (YWKeepWatchPointQrcodeResult)judgeKeepWatchPointWithPatrolLocation:(NSArray* )patrolLocation patrolpointRecord:(NSArray*)patrolpointRecord locationId:(NSInteger)locationId{
    BOOL isPatrolPoint = NO;
//    for (YWPatrolLineLocationRel *locationRel in patrolLocation) {
//        if (locationRel.locationId == locationId) {
//            isPatrolPoint = YES;
//            break;
//        }
//    }
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", locationId];
    NSArray *array = [[patrolLocation filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (array.count>0) {
        isPatrolPoint = YES;
    }
    if (!isPatrolPoint) {
        return YWKeepWatchPointQrcodeResultUnMatch;
    }else{
//        for (YWPatrolPointRecord *pointRecord in patrolpointRecord) {
//            if (pointRecord.locationId == locationId) {
//                return YWKeepWatchPointQrcodeResultHasPatrol;
//            }
//        }
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", locationId];
        NSArray *array = [[patrolpointRecord filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count>0) {
            return YWKeepWatchPointQrcodeResultHasPatrol;
        }
        return YWKeepWatchPointQrcodeResultNoPatrol;
    }
}

- (YWPatrollineRecord *)createLooperRecordWith:(YWKeepWatchMission*)keepWatchMission uniqueTag:(NSString*)uniqueTag{
    YWPatrollineRecord *record = [[YWPatrollineRecord alloc]init];
    record.patrolLineId = keepWatchMission.patrolLine.patrolLineId;
    record.uniqueTag = uniqueTag;
    record.count = 0;
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970]*1000;
    record.startTime = nowTime;
    record.endTime = nowTime;
    record.result = YWPatrollineRecordResultUnfinishAndNormal;
    record.keepWatchMissionId = keepWatchMission.keepWatchMissionId;
    
    NSMutableString *userId = [[NSMutableString alloc] init];
    [keepWatchMission.executors enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (userId.length && idx!=0) {
            [userId appendString:@","];
        }
        [userId appendString:[@(handler.uniqueId) stringValue]];
    }];
    record.executorIds = [NSString stringWithFormat:@"%@",userId];
    return record;
}

- (void)qrcodeSuccessWithMission:(YWKeepWatchMission *)keepWatchMission qrcodeId:(NSString *)qrcodeId noQrcodeLocationId:(NSInteger)noQrcodeLocationId uniqueTag:(NSString *)uniqueTag wReader:(UIViewController *)wReader isFromLedger:(BOOL)isFromLedger{
    NSInteger locationId = 0;
    if (qrcodeId) {
        locationId = [[YWEquipmentManager shareManager]locationIdWithQrcodeId:qrcodeId];
    }else if (noQrcodeLocationId){
        locationId = noQrcodeLocationId;
    }
    NSArray *locationArray = [[YWKeepWatchMissionManager shareManager] allPatrolLocationWithPatrolLineId:keepWatchMission.patrolLine.patrolLineId];
    
    NSArray *pointRecord = [[YWKeepWatchMissionManager shareManager]patrolPointRecordWithUniqueTag:uniqueTag];
    
    YWKeepWatchPointQrcodeResult pointJudge = [[YWKeepWatchMissionManager shareManager]judgeKeepWatchPointWithPatrolLocation:locationArray patrolpointRecord:pointRecord locationId:locationId];
    if (pointJudge==YWKeepWatchPointQrcodeResultUnMatch) {
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(@"isNotKeepWatchLocation", nil);//@"该位置不是巡更点";
        [wReader.navigationController pushViewController:senmVC animated:YES];
    }else if (pointJudge==YWKeepWatchPointQrcodeResultHasPatrol){
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(@"currentLocationHasBeenKeepWatch", nil);//@"该位置已经巡更了";
        [wReader.navigationController pushViewController:senmVC animated:YES];
    }else{
        if (locationId == 0) {
            YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
            senmVC.showContent = NSLocalizedString(@"currentLocationIsError", nil);//@"该巡更位置错误";
            [wReader.navigationController pushViewController:senmVC animated:YES];
        }else{
            YWDoKeepWatchMissionTableViewController *writeInfoVC= [[YWDoKeepWatchMissionTableViewController alloc]init];
            if (isFromLedger) {
                writeInfoVC.isFromLedger = YES;
            }
            writeInfoVC.keepWatchMission = keepWatchMission;
            writeInfoVC.locationId = locationId;
            writeInfoVC.qrcodeId = qrcodeId;
            [wReader.navigationController pushViewController:writeInfoVC animated:YES];
        }
    }
}

- (void)requestPatrolLineWithBuildingId:(NSString *)buildingId Complete:(void(^)(NSArray *lineOptionArray))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);};return;}
    NSDictionary *params = @{@"buildingId": buildingId?:@""};
    NSString *url = [YWCommonTool getAllPatrolLineUrl];
    YWLog(@"url:%@,params:%@",url,params);
    
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* patrolLineOptionArray = [YWPatrolLineOption mj_objectArrayWithKeyValuesArray:json];
        //数据过来不完整（只有id和名字），不保存线路
        if (complete) {
            complete(patrolLineOptionArray);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestPatrolLineWithPatrolLineId:(NSInteger)lineId Complete:(void(^)(YWPatrolLine *patrolLine))complete{
    if (lineId==0) {
        complete(nil);
        return;
    }
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);};return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getOnePatrolLineUrl], (long)lineId];
    YWLog(@"请求单条巡更路线:%@",url);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWPatrolLine* patrolLine = [YWPatrolLine mj_objectWithKeyValues:json];
            //保存线路，线路与巡查任务没有关联
            if (patrolLine) {
                [[YWKeepWatchDBManager shareManager] updatePatrolLineWithLine:patrolLine];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(patrolLine);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)postKeepWatchMissionWithParams:(NSDictionary*)params Complete:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getKeepWatchMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        YWKeepWatchMission* keepWarchMission = [YWKeepWatchMission mj_objectWithKeyValues:json];
        //保存任务
        if (keepWarchMission) {
            [[YWKeepWatchMissionManager shareManager] updateKeepWatchMissionWithArray:@[keepWarchMission]];
            [[YWKeepWatchMissionManager shareManager] requestPatrolLineWithPatrolLineId:keepWarchMission.patrolLine.patrolLineId Complete:^(YWPatrolLine *patrolLine) {
                if (patrolLine) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshAssignKeepWatchMissionNotification object:nil];
                }
                if (complete) {
                    complete(YES);
                }
            }];
        }else{
            if (complete) {
                complete(YES);
            }
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"kTextAssignFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestDeleteKeepWatchMission:(NSInteger)keepWatchMissionId completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getKeepWatchMissionUrl],(long)keepWatchMissionId];
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        BOOL success = [[YWKeepWatchMissionManager shareManager] updateKeepWatchDeleteStatusWithMissionId:keepWatchMissionId];
        if (success) {
            [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeKeepWatch];
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeleteKeepWatchMissionNotification object:nil];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestModifyKeepWatchMission:(NSDictionary *)params completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getKeepWatchMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)createKeepWatchLine:(NSDictionary *)params completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);};return;}
    
    YWLog(@"createKeepWatchLine params --- %@",params);
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getOnePatrolLineUrl] params:params success:^(NSHTTPURLResponse *response, id json) {
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"createLineFailed", nil)];
        }
        if (complete) {
            complete(response.statusCode);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)modifyKeepWatchLine:(NSDictionary *)params completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    YWLog(@"modifyKeepWatchLine params --- %@",params);
    [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getOnePatrolLineUrl] params:params success:^(NSHTTPURLResponse *response, id json) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshModifyPatrolLineNotification object:nil];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyLineFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)deleteKeepWatchLineWithLineId:(NSInteger)patrolLineId completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);};return;}
    
    YWLog(@"deleteKeepWatchLine %ld",(long)patrolLineId);
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getOnePatrolLineUrl],(long)patrolLineId];
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse *response, id json) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeletePatrolLineNotification object:@(patrolLineId)];
        if (complete) {
            complete(response.statusCode);
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else if (response.statusCode ==403){
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailedBecauseOfUnfinishMission", nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        if (complete) {
            complete(response.statusCode);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestKeepWatchMissionPage:(NSInteger)page pageSize:(NSInteger)pageSize WithComplete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    
    NSString *url = [YWCommonTool getKeepWatchMissionUrl];
    YWLog(@"url -- %@,%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* keepWatchMission = [YWKeepWatchMission mj_objectArrayWithKeyValuesArray:json];
        [[YWKeepWatchMissionManager shareManager] updateKeepWatchMissionWithArray:keepWatchMission];
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)requestKeepWatchMissionWithMissionId:(NSInteger)missionId Complete:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getKeepWatchMissionUrl], (long)missionId];
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        YWKeepWatchMission* keepWatchMission = [YWKeepWatchMission mj_objectWithKeyValues:json];
        if (keepWatchMission) {
            [[YWKeepWatchMissionManager shareManager] updateKeepWatchMissionWithArray:@[keepWatchMission]];
        }
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
//        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
//            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
//        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestKeepWatchMissionInfo:(NSInteger)keepWatchMissionId complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString *url = [YWCommonTool getKeepWatchMissionInfoUrl];
    NSDictionary *params = @{@"keepWatchMissionId":@(keepWatchMissionId)};
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWKeepWatchMissionInfoJson* keepWatchMissionInfoJson = [YWKeepWatchMissionInfoJson mj_objectWithKeyValues:json];
            if (keepWatchMissionInfoJson) {
                //更新任务的最新一条记录
                [[YWKeepWatchMissionManager shareManager] updatePatrollineRecordWithNewWorkData:keepWatchMissionInfoJson.latestRecord?@[keepWatchMissionInfoJson.latestRecord]:nil];
                
                NSArray *totalPointRecordArray = keepWatchMissionInfoJson.latestRecord.details;
                __block NSMutableArray *picturesArray = totalPointRecordArray.count ? [NSMutableArray array] : nil;
                [totalPointRecordArray enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull detailPointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    detailPointRecord.patrolLineId = keepWatchMissionInfoJson.latestRecord.patrolLine.patrolLineId;
                    detailPointRecord.uniqueTag = keepWatchMissionInfoJson.latestRecord.uniqueTag;
                    detailPointRecord.locationId = detailPointRecord.location.locationId;
                    detailPointRecord.patrolpointRecordId = [NSString stringWithFormat:@"%@_%ld",detailPointRecord.uniqueTag,(long)detailPointRecord.locationId];
                    detailPointRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
                    detailPointRecord.sort = [[YWKeepWatchMissionManager shareManager]sortWithLocationId:detailPointRecord.locationId patrolLineId:detailPointRecord.patrolLineId];
                    [detailPointRecord.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                        patrolPicture.recordId = detailPointRecord.patrolpointRecordId;
                        patrolPicture.pictureId = [YWCommonTool randStringId];
                        patrolPicture.pictureName = @"";
                        patrolPicture.isLocalImage = NO;
                        patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                        patrolPicture.recordType = YWPictureRecordTypePatrol;
                        [picturesArray addObject:patrolPicture];
                    }];
                    
                    //是否建立与报障的关联
                    [detailPointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:detailPointRecord.detailUniqueTag]) {
                            [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:detailPointRecord.detailUniqueTag];
                        }
                    }];
                }];
                [[YWKeepWatchMissionManager shareManager] updatePatrolPointRecordWithArray:totalPointRecordArray];
                [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
            }
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestPatrolLineWithLineArray:(NSArray *)patrolLineArray complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString* url = [YWCommonTool getPatrolLineDetailUrl];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [patrolLineArray enumerateObjectsUsingBlock:^(YWPatrolLine*  _Nonnull patrolLine, NSUInteger idx, BOOL * _Nonnull stop) {
        [params setValue:@(patrolLine.patrolLineId) forKey:[NSString stringWithFormat:@"patrolLines[%lu].patrolLineId",(unsigned long)idx]];
        if (patrolLine.updateTime) {
            [params setValue:@(patrolLine.updateTime) forKey:[NSString stringWithFormat:@"patrolLines[%lu].updateTime",(unsigned long)idx]];
        }
    }];
    YWLog(@"url---%@,%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSArray* patrolLineArray = [YWPatrolLine mj_objectArrayWithKeyValuesArray:json];
            //保存线路
            if (patrolLineArray.count) {
                [[YWKeepWatchDBManager shareManager] updatePatrolLine:patrolLineArray];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestTheLatestLineRecordWithKeepWatchMissionIds:(NSString *)keepWatchMissionIds complete:(void (^)(BOOL))complete{
    if (keepWatchMissionIds.length==0) {
        return;
    }
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSDictionary *params = @{@"keepWatchMissionIds" : keepWatchMissionIds?:@""};
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getTheLatestPointRecordUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* patrolPointRecordArray = [YWPatrolPointRecordJson mj_objectArrayWithKeyValuesArray:json];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            __block NSMutableArray *totalPointRecordArray = [NSMutableArray array];
            __block NSMutableArray *picturesArray = [NSMutableArray array];
            [patrolPointRecordArray enumerateObjectsUsingBlock:^(YWPatrolPointRecordJson*  _Nonnull pointJson, NSUInteger idx, BOOL * _Nonnull stop) {
                [pointJson.details enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull detailPointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    detailPointRecord.patrolLineId = pointJson.patrolLine.patrolLineId;
                    detailPointRecord.uniqueTag = pointJson.uniqueTag;
                    detailPointRecord.locationId = detailPointRecord.location.locationId;
                    detailPointRecord.patrolpointRecordId = [NSString stringWithFormat:@"%@_%ld",detailPointRecord.uniqueTag,(long)detailPointRecord.locationId];
                    detailPointRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
                    detailPointRecord.sort = [[YWKeepWatchMissionManager shareManager]sortWithLocationId:detailPointRecord.locationId patrolLineId:detailPointRecord.patrolLineId];
                    [detailPointRecord.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                        patrolPicture.recordId = detailPointRecord.patrolpointRecordId;
                        patrolPicture.pictureId = [YWCommonTool randStringId];
                        patrolPicture.pictureName = @"";
                        patrolPicture.isLocalImage = NO;
                        patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                        patrolPicture.recordType = YWPictureRecordTypePatrol;
                        [picturesArray addObject:patrolPicture];
                    }];
                    [totalPointRecordArray addObject:detailPointRecord];
                    //是否建立与报障的关联
                    [detailPointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:detailPointRecord.detailUniqueTag]) {
                            [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:detailPointRecord.detailUniqueTag];
                        }
                    }];
                }];
            }];
            [[YWKeepWatchMissionManager shareManager] updatePatrolPointRecordWithArray:totalPointRecordArray];
            [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestPatrolLineRecordOfMeWithPage:(NSInteger)page pageSize:(NSInteger)pageSize complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
       [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool getPatrolLineRecordUrl];
    YWLog(@"url---%@,param---%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSArray* patrolLineRecord = [YWPatrollineRecord mj_objectArrayWithKeyValuesArray:json];
            NSMutableArray *keepWatchMissionArray = [NSMutableArray array];
            
            [patrolLineRecord enumerateObjectsUsingBlock:^(YWPatrollineRecord*  _Nonnull lineRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                
                YWKeepWatchMission *keepWatchMission = [[YWKeepWatchMission alloc] init];
                keepWatchMission.keepWatchMissionId = lineRecord.keepWatchMissionId;
                keepWatchMission.buildingId = lineRecord.buildingId;
                keepWatchMission.creator = lineRecord.missionCreator;
                keepWatchMission.missionSequence = lineRecord.missionSequence;
                keepWatchMission.status = -2;
                [keepWatchMissionArray addObject:keepWatchMission];
            }];
            [[YWKeepWatchMissionManager shareManager] updatePatrollineRecordWithNewWorkData: patrolLineRecord];
            [[YWKeepWatchMissionManager shareManager] updateKeepWatchMissionWithArray:keepWatchMissionArray];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(YES);
                }
            });
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestPatrolLineRecordWithPage:(NSInteger)page pageSize:(NSInteger)pageSize keepWatchMissionId:(NSInteger)keepWatchMissionId complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (keepWatchMissionId > 0) {
        [params setObject:@(keepWatchMissionId) forKey:@"keepWatchMissionId"];
    }
    if (page) {
        [params setObject:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setObject:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool getPatrolLineRecordUrl];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* patrolLineRecord = [YWPatrollineRecord mj_objectArrayWithKeyValuesArray:json];
        
        [[YWKeepWatchMissionManager shareManager] updatePatrollineRecordWithNewWorkData:patrolLineRecord];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
             [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestPatrolPointRecord:(NSString*)uniqueTag WithComplete:(void(^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",[YWCommonTool getPatrolLineRecordUrl],uniqueTag];
    YWLog(@"请求所有巡更点记录:%@",url);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWPatrolPointRecordJson* pointJson = [YWPatrolPointRecordJson mj_objectWithKeyValues:json];
            if (pointJson.details.count>0) {
                __block NSMutableArray *totalPointRecordArray = [NSMutableArray array];
                __block NSMutableArray *picturesArray = [NSMutableArray array];
                [pointJson.details enumerateObjectsUsingBlock:^(YWPatrolPointRecord*  _Nonnull detailPointRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    detailPointRecord.patrolLineId = pointJson.patrolLine.patrolLineId;
                    detailPointRecord.uniqueTag = pointJson.uniqueTag;
                    detailPointRecord.locationId = detailPointRecord.location.locationId;
                    detailPointRecord.patrolpointRecordId = [NSString stringWithFormat:@"%@_%ld",detailPointRecord.uniqueTag,(long)detailPointRecord.locationId];
                    detailPointRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
                    detailPointRecord.sort = [[YWKeepWatchMissionManager shareManager]sortWithLocationId:detailPointRecord.locationId patrolLineId:detailPointRecord.patrolLineId];
                    [detailPointRecord.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                        patrolPicture.recordId = detailPointRecord.patrolpointRecordId;
                        patrolPicture.pictureId = [YWCommonTool randStringId];
                        patrolPicture.pictureName = @"";
                        patrolPicture.isLocalImage = NO;
                        patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                        patrolPicture.recordType = YWPictureRecordTypePatrol;
                        [picturesArray addObject:patrolPicture];
                    }];
                    [totalPointRecordArray addObject:detailPointRecord];
                    //是否建立与报障的关联
                    [detailPointRecord.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:detailPointRecord.detailUniqueTag]) {
                            [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:detailPointRecord.detailUniqueTag];
                        }
                    }];
                }];
                [[YWKeepWatchMissionManager shareManager] updatePatrolPointRecordWithArray:totalPointRecordArray];
                [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (complete) {
                        complete(YES);
                    }
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (complete) {
                        complete(YES);
                    }
                });
            }
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
            }
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestPatrolPointRecord:(NSInteger)locationId page:(NSInteger)page pageSize:(NSInteger)pageSize complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@(locationId) forKey:@"locationId"];
    if (page) {
        [params setObject:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setObject:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool getKeepWatchLocationRecordUrl];
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray *keepWatchlLcationArray = [YWKeepWatchLocationRecordJson mj_objectArrayWithKeyValuesArray:json];
        __block NSMutableArray *totalPointRecordArray = [NSMutableArray array];
        __block NSMutableArray *picturesArray = [NSMutableArray array];
        __block YWPatrolPointRecord *pointRecord = nil;
        
        [keepWatchlLcationArray enumerateObjectsUsingBlock:^(YWKeepWatchLocationRecordJson*  _Nonnull locationRecordJson, NSUInteger idx, BOOL * _Nonnull stop) {
            pointRecord = [[YWPatrolPointRecord alloc]init];
            pointRecord.patrolLineId = 0;
            pointRecord.uniqueTag = locationRecordJson.uniqueTag;
            pointRecord.detailUniqueTag = locationRecordJson.detailUniqueTag;
            
            pointRecord.patrolTime = locationRecordJson.executeTime;
            pointRecord.executor = locationRecordJson.executor;
            pointRecord.locationId = locationId;
            pointRecord.note = locationRecordJson.note;
            pointRecord.patrolpointRecordId = [NSString stringWithFormat:@"%@_%ld",pointRecord.uniqueTag,(long)pointRecord.locationId];
            pointRecord.status = locationRecordJson.status;
            pointRecord.uploadStatus = YWPatrolPointRecordUploadStatusFinished;
            pointRecord.sort = -1;
            [locationRecordJson.pictures enumerateObjectsUsingBlock:^(YWPatrolPicture*  _Nonnull patrolPicture, NSUInteger idx, BOOL * _Nonnull stop) {
                patrolPicture.recordId = pointRecord.patrolpointRecordId;
                patrolPicture.pictureId = [YWCommonTool randStringId];
                patrolPicture.pictureName = @"";
                patrolPicture.isLocalImage = NO;
                patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
                patrolPicture.recordType = YWPictureRecordTypePatrol;
                [picturesArray addObject:patrolPicture];
            }];
            [totalPointRecordArray addObject:pointRecord];
            //是否建立与报障的关联
            [locationRecordJson.posTroubleArray enumerateObjectsUsingBlock:^(YWTroubleIdJson*  _Nonnull troubleIdJson, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![[YWMissionManager shareManager] isExistRelWithTroubleId:troubleIdJson.troubleId detailUniqueTag:pointRecord.detailUniqueTag]) {
                    [[YWMissionManager shareManager] saveRecordAndPostTroubleRelWithtroubleId:troubleIdJson.troubleId detailUniqueTag:pointRecord.detailUniqueTag];
                }
            }];
        }];
        [[YWKeepWatchMissionManager shareManager] updatePatrolPointRecordWithArray:totalPointRecordArray];
        [[YWKeepWatchMissionManager shareManager] updatePatrolPictureWithNewWorkData:picturesArray];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestKeepWatchMissionStatusWithIds:(NSString *)ids Complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);};return;}
    
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getKeepWatchMissionStatusUrl] params:@{@"missionIds" : ids?:@""} success:^(NSHTTPURLResponse* response, id json) {
        NSArray* missions = [YWKeepWatchMission mj_objectArrayWithKeyValuesArray:json];
        [missions enumerateObjectsUsingBlock:^(YWKeepWatchMission*  _Nonnull keepWatchMission, NSUInteger idx, BOOL * _Nonnull stop) {
            if (keepWatchMission.status == -1) {
                [self updateKeepWatchDeleteStatusWithMissionId:keepWatchMission.keepWatchMissionId];
            }else{
                YWLoginUser *currentUser = [YWLoginTool loginUser];
                if (keepWatchMission.creator.uniqueId != currentUser.uniqueId && ![YWCommonTool containSelfInHandlers:keepWatchMission.executors] && ![keepWatchMission.observerIds containsString:@(currentUser.uniqueId).stringValue]){
                    [self updateKeepWatchDeleteStatusWithMissionId:keepWatchMission.keepWatchMissionId];
                }
            }
        }];
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (NSArray*)matchKeepWatchMissionsWithQrcodeID:(NSString*)qrcodeId orLocationId:(NSInteger)locationId
{
    NSInteger myLocationId = qrcodeId ? [[YWEquipmentManager shareManager]locationIdWithQrcodeId:qrcodeId] : locationId;
    NSArray* keepWatchMissions = [[YWKeepWatchMissionManager shareManager] keepWatchMissionWithLocationId:myLocationId];
    NSMutableArray* missionArray = [NSMutableArray array];
    if (keepWatchMissions.count) {
        [keepWatchMissions enumerateObjectsUsingBlock:^(YWKeepWatchMission* _Nonnull keepWatchMission, NSUInteger idx, BOOL* _Nonnull stop) {
            YWKeepWatchMission *mission = [self judgeTheRightKeepWatchMission:keepWatchMission qrcodeId:qrcodeId orLocationId:myLocationId];
            if (mission) {
                [missionArray addObject:mission];
            }
        }];
    }
    return missionArray;
}
- (YWKeepWatchMission*)judgeTheRightKeepWatchMission:(YWKeepWatchMission*)keepWatchMission qrcodeId:(NSString*)qrcodeId orLocationId:(NSInteger)locationId
{
    YWKeepWatchJudgeType judgeType = [[YWKeepWatchMissionManager shareManager] judgeTypeWithMission:keepWatchMission];
    if (judgeType != YWKeepWatchJudgeTypeMatch) {
        //[YWCommonTool showTextHUDWithContent:[[YWKeepWatchMissionManager shareManager] typeNameWithJudgeType:judgeType]];
        return nil;
    }
    
    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:keepWatchMission];
    __block YWPatrollineRecord *looperRecord = [[YWKeepWatchMissionManager shareManager] latestPatrollineRecordWithUniqueTag:uniqueTag];
    
    NSInteger myLocationId = qrcodeId ? [[YWEquipmentManager shareManager]locationIdWithQrcodeId:qrcodeId] : locationId;
    NSArray *locationArray = [[YWKeepWatchMissionManager shareManager] allPatrolLocationWithPatrolLineId:keepWatchMission.patrolLine.patrolLineId];
    NSArray *pointRecord = [[YWKeepWatchMissionManager shareManager]patrolPointRecordWithUniqueTag:looperRecord.uniqueTag];
    
    YWKeepWatchPointQrcodeResult pointJudge = [[YWKeepWatchMissionManager shareManager]judgeKeepWatchPointWithPatrolLocation:locationArray patrolpointRecord:pointRecord locationId:myLocationId];
    if (pointJudge==YWKeepWatchPointQrcodeResultUnMatch) {
        return nil;
    }else if (pointJudge==YWKeepWatchPointQrcodeResultHasPatrol){
        return nil;
    }else{
        if (looperRecord) {
            if (looperRecord.result >= YWPatrollineRecordResultFinishAndTrouble) {
                return nil;
            }else{
                return keepWatchMission;
            }
        }else{
            return keepWatchMission;
        }
    }
}
@end
